package com.ipDev.moyvSys.controller.emp;

import com.ipDev.moyvSys.constant.JwtClaimsConstant;
import com.ipDev.moyvSys.domain.dto.EmpLoginDTO;
import com.ipDev.moyvSys.domain.po.Employee;
import com.ipDev.moyvSys.domain.vo.EmpLoginVO;
import com.ipDev.moyvSys.properties.JwtProperties;
import com.ipDev.moyvSys.service.IEmployeeService;
import com.ipDev.moyvSys.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import com.ipDev.moyvSys.utils.Result;


@RestController
@RequestMapping("/emp/emp")
@Slf4j
@RequiredArgsConstructor
public class EmpController {
    private final IEmployeeService employeeService;
    private final JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<EmpLoginVO> login(@RequestBody EmpLoginDTO empLoginDTO) {
        log.info("职工登录:{}", empLoginDTO);
        Employee emp = employeeService.login(empLoginDTO);
        log.info("login返回:{}", emp);
        if (emp == null) {
            log.info("登录失败!");
            return Result.error("登录失败!");
        }
        //登录成功后给职工发放令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, emp.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getEmpSecretKey(),
                jwtProperties.getEmpTtl(),
                claims);

        EmpLoginVO vo = EmpLoginVO.builder().id(emp.getId())
                .name(emp.getName())
                .admin(emp.getAdmin())
                .token(token)
                .build();
        return Result.success(vo);
    }
}
